<?php
/**
 * Created by PhpStorm.
 * User: JYuans
 * Date: 2019/11/29
 * Time: 10:55
 */
namespace Bstage\Controller;

use Common\Model\CommonModel;
use Think\Page;

class MidExamineController extends BstageController {

    /**
     * 中层考核列表查询
     */
    public function midExamineQuery(){
        //分页
        $now_page = $_REQUEST['now_page']?$_REQUEST['now_page']:1;//默认第一页
        $page_size = $_REQUEST['page_size']?$_REQUEST['page_size']:50;//默认每页50条
        //查询条件
        $where = array();
        //筛选姓名
        if($_REQUEST["search_title"]){
            $where['title'] = ['like','%'.$_REQUEST['search_title'].'%'];
        }

        $field = "mid_ex_id,status,title,add_time";
        $list_data = M('MidExamine')
            ->where($where)
            ->field($field)
            ->order('add_time DESC')
            ->page($now_page,$page_size)
            ->select();

        if(!$list_data) {
            $this->returnJson(503,'没有更多数据');
        }

        $status_str_array = ["未开始","进行中","已结束"];
        foreach($list_data as $key=>$value){
            $list_data[$key]['status_str'] = $status_str_array[$value['status']];

            $item_array = M("MidExamineItem")
                ->where(['mid_ex_id'=>$value['mid_ex_id']])
                ->getField("title",true);
            $list_data[$key]['item_str'] = implode(",", $item_array);

            $list_data[$key]['add_time'] = changeDateTime($value['add_time']);
        }

        $count = M('MidExamine')
            ->where($where)
            ->count();

        $return_data = array();
        $return_data['list_data'] = $list_data;
        $return_data['count'] = $count;
        $return_data['now_page'] = $now_page;
        $return_data['page_size'] = $page_size;
        $return_data['max_page'] = ceil($count / $page_size);

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 添加中层考核接口
     */
    public function addMidExamineAction(){
        $new_data = array();
        $new_data['status'] = 0;
        $new_data['title'] = $_REQUEST['title']?$_REQUEST['title']:$this->errorReturn("请输入中层考核名称");
        $new_data['add_time'] = time();

        $item_json = $_REQUEST['item_json']?trim($_REQUEST['item_json']):$this->errorReturn("请输入中层考核指标");

        $model = M();
        $model->startTrans();

        $add_result = M("MidExamine")
            ->add($new_data);

        if(!$add_result){
            $model->rollback();
            $this->errorReturn("添加考核失败，请重新尝试");
        }

        $item_array = json_decode($item_json,true);
        if(count($item_array) > 0){
            for($i=0;$i<count($item_array);$i++){
                $new_item_data = array();
                $new_item_data['mid_ex_id'] = $add_result;
                $new_item_data['title'] = $item_array[$i];

                $add_item_result = M("MidExamineItem")
                    ->add($new_item_data);

                if(!$add_item_result){
                    $model->rollback();
                    $this->errorReturn("添加考核指标失败，请重新尝试");
                }
            }
        }else{
            $model->rollback();
            $this->errorReturn("指标参数不能为空");
        }

        $model->commit();
        $this->successReturn("添加成功");
    }

    /**
     * 修改中层考核信息接口
     */
    public function editMidExamineAction(){
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");

        $new_data = array();
        $new_data['title'] = $_REQUEST['title']?$_REQUEST['title']:$this->errorReturn("请输入中层考核名称");
        $new_data['update_time'] = time();

        $update_result = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->save($new_data);

        if(!$update_result){
            $this->errorReturn("更新考核信息失败，请重新尝试");
        }

        $this->successReturn("修改成功");
    }

    /**
     * 设置中层互评时间接口
     */
    public function editExamineSameTime(){
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");

        $new_data = array();
        $new_data['same_start_time'] = $_REQUEST['start_time']?strtotime($_REQUEST['start_time']):$this->errorReturn("请输入开始时间");
        $new_data['same_end_time'] = $_REQUEST['end_time']?strtotime($_REQUEST['end_time'])+86399:$this->errorReturn("请输入结束时间");

        if($new_data['same_start_time'] > $new_data['same_end_time']){
            $this->errorReturn("开始时间不能大于结束时间");
        }

        if($new_data['same_end_time'] < time()){
            $this->errorReturn("结束时间无法设置为过去时间");
        }

        $new_data['update_time'] = time();

        $update_result = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->save($new_data);
        if($update_result){
            $this->successReturn("修改成功");
        }else{
            $this->errorReturn("修改失败,请重新尝试");
        }
    }

    /**
     * 设置上级评审时间接口
     */
    public function editExamineUpTime(){
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");

        $new_data = array();
        $new_data['up_start_time'] = $_REQUEST['start_time']?strtotime($_REQUEST['start_time']):$this->errorReturn("请输入开始时间");
        $new_data['up_end_time'] = $_REQUEST['end_time']?strtotime($_REQUEST['end_time'])+86399:$this->errorReturn("请输入结束时间");
        $new_data['update_time'] = time();

        if($new_data['up_start_time'] > $new_data['up_end_time']){
            $this->errorReturn("开始时间不能大于结束时间");
        }

        if($new_data['up_end_time'] < time()){
            $this->errorReturn("结束时间无法设置为过去时间");
        }

        $update_result = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->save($new_data);
        if($update_result){
            $this->successReturn("修改成功");
        }else{
            $this->errorReturn("修改失败,请重新尝试");
        }
    }

    /**
     * 获取中层考核基础详情
     */
    public function getMidExamineInfoAction(){
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");

        $mid_ex_data = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field('mid_ex_id,status,title,add_time')
            ->find();
        if(!$mid_ex_data){
            $this->errorReturn("中层考核ID错误，请重新尝试");
        }
        $status_str_array = ["未开始","进行中","已结束"];
        $mid_ex_data['status_str'] = $status_str_array[$mid_ex_data['status']];
        $mid_ex_data['add_time'] = changeDateTime($mid_ex_data['add_time']);

        $item_list = M("MidExamineItem")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("item_id,title,sort")
            ->select();
        if(!$item_list){
            $item_list = array();
        }
        $mid_ex_data['item_list'] = $item_list;

        $this->successReturn("获取成功",$mid_ex_data);
    }

    /**
     * 删除中层考核接口
     */
    public function deleteMidExamineAction(){
        $mid_ex_id = $_REQUEST['id_str'] ? $_REQUEST['id_str'] : $this->errorReturn("缺少中层考核ID");

        $delete_examine = M("MidExamine")
            ->where(['mid_ex_id'=>['in',$mid_ex_id]])
            ->delete();

        if(!$delete_examine){
            $this->errorReturn("删除考核失败，请重新尝试");
        }

        M("MidExamineItem")
            ->where(['mid_ex_id'=>['in',$mid_ex_id]])
            ->delete();

        M("MidExamineUpRelation")
            ->where(['mid_ex_id'=>['in',$mid_ex_id]])
            ->delete();

        M("MidExamineDownRelation")
            ->where(['mid_ex_id'=>['in',$mid_ex_id]])
            ->delete();

        M("MidExamineSameRelation")
            ->where(['mid_ex_id'=>['in',$mid_ex_id]])
            ->delete();

        M("MidExamineResult")
            ->where(['mid_ex_id'=>['in',$mid_ex_id]])
            ->delete();

        $this->successReturn("删除考核成功");
    }

    /**
     * 添加临时账号方法
     */
    public function addTemporaryUser(){
        $user_count = is_numeric($_REQUEST["user_count"])?$_REQUEST["user_count"]:$this->errorReturn("请输入需要生成的账号数量，参数必须为数字");

        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");
        $depart_id = $_REQUEST["depart_id"]?$_REQUEST["depart_id"]:$this->errorReturn("请选择所属部门");

        $check_depart_id = M("Department")
            ->where(['depart_id'=>$depart_id])
            ->count();
        if(!$check_depart_id){
            $this->errorReturn("部门ID错误");
        }

        if($user_count <= 0){
            $this->errorReturn("生成账号数量必须大于0");
        }

        $new_data = array();
        $new_data['depart_id'] = $depart_id;
        $new_data['rank'] = 1;
        $new_data['user_type'] = 0;
        $new_data['add_time'] = time();
        $new_data['use_start_time'] = $_REQUEST["use_start_time"]?strtotime($_REQUEST["use_start_time"]):$this->errorReturn("请输入临时账号使用期限，开始时间");
        $new_data['use_end_time'] = $_REQUEST["use_end_time"]?strtotime($_REQUEST["use_end_time"])+86399:$this->errorReturn("请输入临时账号使用期限，结束时间");
        if($new_data['use_start_time'] >= $new_data['use_end_time']){
            $this->errorReturn("期限结束时间必须大于当前时间");
        }

        //获取临时账号前缀标识
        /*$username_flag = $this->generateTemporaryUsername();
        if(!$username_flag){
            $this->errorReturn("获取临时账号标识失败，请重新尝试");
        }

        //获取临时账号后续字符串
        $str_len = strlen($user_count);
        $str_flag = "";
        for($i = 0;$i < $str_len;$i++){
            $str_flag = $str_flag."0";
        }*/

        //获取该部门所有中层人员，depart_id,rank
        $mid_user_list = M("User")
            ->where(['depart_id'=>$depart_id,'rank'=>['in','3,4']])
            ->field("user_id")
            ->select();

        if(!$mid_user_list){
            $this->errorReturn("该部门无中层人员，无法添加临时账号");
        }

        $model = M();
        $model->startTrans();

        //循环生成账号数据
        for($i = 0;$i < $user_count;$i++){
            /*$current_i = $i + 1;
            $new_data['username'] = "M".$username_flag.mb_substr($str_flag,0,$str_len - strlen($current_i)).$current_i;
            $new_data['password'] = md5($new_data['username']);*/
            do{
                $new_data['username'] = randnumkeys(8);
                $check_username = M("User")
                    ->where(['username'=>$new_data['username']])
                    ->count();
            }while($check_username);

            $new_data['t_user_pass'] = randnumkeys(8);
            $new_data['password'] = md5($new_data['t_user_pass']);
            $new_data['name'] = $new_data['username'];

            $add_user_result = M("User")
                ->add($new_data);
            if(!$add_user_result){
                $model->rollback();
                $this->errorReturn("添加账号失败，请重新尝试");
            }

            //mid_ex_id,be_examine_user_id,examine_user_id,status,examine_result,score,percentile_score
            foreach($mid_user_list as $key=>$value){
                $new_down_relation = array();
                $new_down_relation['mid_ex_id'] = $mid_ex_id;
                $new_down_relation['be_examine_user_id'] = $value['user_id'];
                $new_down_relation['examine_user_id'] = $add_user_result;
                $new_down_relation['depart_id'] = $depart_id;
                $new_down_relation['use_end_time'] = strtotime($_REQUEST["use_end_time"])+86399;

                $add_down_relation_result = M("MidExamineDownRelation")
                    ->add($new_down_relation);
                if(!$add_down_relation_result){
                    $model->rollback();
                    $this->errorReturn("添加账号关系失败，请重新尝试");
                }
            }
        }

        $model->commit();
        $this->successReturn("临时账号生成成功");
    }

    /**
     * 获取临时账号接口
     */
    public function getTemporaryUserList(){
        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");
        $depart_id = $_REQUEST["depart_id"]?$_REQUEST["depart_id"]:$this->errorReturn("请选择所属部门");

        $down_relation_list = M("mid_examine_down_relation")
            ->where(['mid_ex_id'=>$mid_ex_id,'depart_id'=>$depart_id])
            ->getField("examine_user_id",true);
        if(!$down_relation_list){
            $this->returnJson(503,"无数据");
        }

        $user_list = M("User")
            ->where(['user_id'=>['in',$down_relation_list]])
            ->field("username,t_user_pass")
            ->select();
        if(!$user_list){
            $this->returnJson(503,"无数据");
        }
        foreach($user_list as $key=>$value){
            $user_list[$key]['password'] = $value['t_user_pass'];
        }

        $this->successReturn("获取成功",$user_list);
    }

    /**
     * 获取考核中层干部列表
     */
    public function getMidUserList(){
        //分页
        $now_page = $_REQUEST['now_page']?$_REQUEST['now_page']:1;//默认第一页
        $page_size = $_REQUEST['page_size']?$_REQUEST['page_size']:50;//默认每页50条
        //是否获取全部
        $is_all = $_REQUEST["is_all"]?$_REQUEST["is_all"]:0;

        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");

        $mid_ex_data = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("same_start_time,same_end_time")
            ->find();

        $hide_user_id = $_REQUEST['hide_user_id'] ? $_REQUEST['hide_user_id'] : 0;

        $where = array();
        //筛选部门
        if($_REQUEST["search_depart_id"]){
            $where['depart_id'] = $_REQUEST['search_depart_id'];
        }
        //筛选级别
        if($_REQUEST["search_rank"] && ($_REQUEST["search_rank"] == 3 || $_REQUEST["search_rank"] == 4)){
            $where['rank'] = $_REQUEST['search_rank'];
        }else{
            $where['rank'] = ['in','3,4'];
        }
        //筛选姓名
        if($_REQUEST["search_name"]){
            $where['name'] = ['like','%'.$_REQUEST['search_name'].'%'];
        }
        //筛选职务
        if($_REQUEST["search_station"]){
            $where['station'] = ['like','%'.$_REQUEST['search_station'].'%'];
        }

        $be_examine_user_id_list = array();
        if($hide_user_id){
            $where['user_id'] = ['neq',$hide_user_id];

            $be_examine_user_id_list = M("MidExamineSameRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'examine_user_id'=>$hide_user_id])
                ->getField("be_examine_user_id",true);
            if(!$be_examine_user_id_list){
                $be_examine_user_id_list = array();
            }
        }

        $field = "user_id,depart_id,number,name,phone,email,rank,station";

        if($is_all){
            $list_data = M("User")
                ->where($where)
                ->order("user_id")
                ->field($field)
                ->select();
        }else{
            $list_data = M("User")
                ->where($where)
                ->order("user_id")
                ->field($field)
                ->page($now_page,$page_size)
                ->select();
        }

        if(!$list_data){
            $this->returnJson(503,'没有更多数据');
        }

        $depart_name_array = array();
        if($list_data){
            $depart_id_array = array_column($list_data,'depart_id');

            $depart_name_array = M("Department")
                ->where(['depart_id'=>['in',$depart_id_array]])
                ->getField("depart_id,name");
        }

        foreach($list_data as $key=>$value) {
            $list_data[$key]['depart_name'] = isset($depart_name_array[$value['depart_id']])?$depart_name_array[$value['depart_id']]:"";

            $list_data[$key]['rank'] = CommonModel::rank_str_array[$value['rank']];

            $list_data[$key]['examine_mid_count'] = M("MidExamineSameRelation")
                ->where(['mid_ex_id' => $mid_ex_id, 'examine_user_id' => $value['user_id']])
                ->count();
            $list_data[$key]['examine_mid_complete_count'] = M("MidExamineSameRelation")
                ->where(['mid_ex_id' => $mid_ex_id, 'examine_user_id' => $value['user_id'],'status'=>1])
                ->count();
            if($list_data[$key]['examine_mid_count'] == 0){
                $list_data[$key]['examine_mid_result'] = "";
            }else{
                if($list_data[$key]['examine_mid_count'] == $list_data[$key]['examine_mid_complete_count']){
                    $list_data[$key]['examine_mid_result'] = "已完成";
                }else{
                    $list_data[$key]['examine_mid_result'] = "未完成";
                }
            }

            $list_data[$key]['be_examine_mid_count'] = M("MidExamineSameRelation")
                ->where(['mid_ex_id' => $mid_ex_id, 'be_examine_user_id' => $value['user_id']])
                ->count();
            $list_data[$key]['be_examine_mid_complete_count'] = M("MidExamineSameRelation")
                ->where(['mid_ex_id' => $mid_ex_id, 'be_examine_user_id' => $value['user_id'],'status'=>1])
                ->count();
            if($list_data[$key]['be_examine_mid_count'] == 0){
                $list_data[$key]['be_examine_mid_result'] = "";
            }else{
                if($list_data[$key]['be_examine_mid_count'] == $list_data[$key]['be_examine_mid_complete_count']){
                    $list_data[$key]['be_examine_mid_result'] = "已完成";
                }else{
                    $list_data[$key]['be_examine_mid_result'] = "未完成";
                }
            }

            $list_data[$key]['examine_up_count'] = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$value['user_id']])
                ->count();
            $list_data[$key]['examine_up_complete_count'] = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$value['user_id'],'status'=>1])
                ->count();

            if($list_data[$key]['examine_up_count'] == 0){
                $list_data[$key]['examine_up_result'] = "";
            }else{
                if($list_data[$key]['examine_up_count'] == $list_data[$key]['examine_up_complete_count']){
                    $list_data[$key]['examine_up_result'] = "已完成";
                }else{
                    $list_data[$key]['examine_up_result'] = "未完成";
                }
            }
        }

        $count = M('User')
            ->where($where)
            ->count();

        $return_data = array();
        $return_data['list_data'] = $list_data;
        $return_data['be_examine_user_id_list'] = $be_examine_user_id_list;
        $return_data['start_time'] = changeDate($mid_ex_data['same_start_time']);
        $return_data['end_time'] = changeDate($mid_ex_data['same_end_time']);
        $return_data['count'] = $count;
        $return_data['now_page'] = $now_page;
        $return_data['page_size'] = $page_size;
        $return_data['max_page'] = ceil($count / $page_size);

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 获取中层考核上级关系列表接口
     */
    public function getUpUserList(){
        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");
        $user_id = $_REQUEST['user_id'] ? $_REQUEST['user_id'] : $this->errorReturn("缺少中层人员ID");

        $user_data = M("User")
            ->where(['user_id'=>$user_id])
            ->field("depart_id,rank")
            ->find();

        $all_up_user_list = array();

        //普通上级
        $up_user_list = M("User")
            ->where(['rank'=>5])
            ->field("user_id,name,station,rank")
            ->select();

        foreach($up_user_list as $key=>$value){
            $value['up_type_str'] = "高管";

            $all_up_user_list[] = $value;
        }
        unset($up_user_list);

        //如果是中层副职才获取直接上级
        if($user_data['rank'] == 3) {
            //直接上级
            $depart_up_user_list = M("User")
                ->where(['depart_id' => $user_data['depart_id'], 'rank' => 4])
                ->field("user_id,name,station,rank")
                ->select();
            foreach ($depart_up_user_list as $key => $value) {
                $value['up_type_str'] = "直接上级";

                $all_up_user_list[] = $value;
            }
            unset($depart_up_user_list);
        }

        if(!$all_up_user_list){
            $this->returnJson(503,'无高层数据');
        }

        //获取该中层人员的上级考核关系
        $user_up_relation = M("MidExamineUpRelation")
            ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id])
            ->field("examine_user_id,weight")
            ->select();
        if(!$user_up_relation){
            $user_up_relation = array();
        }

        foreach($user_up_relation as $key=>$value){
            $user_up_relation[$key]['weight'] = bcmul($value['weight'],100);
        }

        $return_data = array();
        $return_data['up_user_list'] = $all_up_user_list;
        $return_data['up_relation'] = $user_up_relation;

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 获取部门下级员工审核情况列表接口
     */
    public function getDownDepartList(){
        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");

        //获取所有下级评审数据
        $mid_examine_down_relation_list = M("MidExamineDownRelation")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("depart_id,status,use_end_time,can_examine_status")
            ->group("examine_user_id")
            ->select();

        $depart_id_array = array_column($mid_examine_down_relation_list,"depart_id");
        if(!$depart_id_array){
            $this->returnJson("503","无数据");
        }

        //获取所有部门数据
        $depart_list = M("Department")
            ->where(['depart_id'=>['in',$depart_id_array]])
            ->getField("depart_id,name,add_time");
        if(!$depart_list){
            $this->returnJson("503","无数据");
        }

        //预处理部门数据
        foreach($depart_list as $key=>$value){
            $depart_list[$key]['amount_count'] = 0;
            $depart_list[$key]['complete_count'] = 0;
        }
        //处理下级评审数据
        $can_examine_status_str = ["进行中","已结束"];
        foreach($mid_examine_down_relation_list as $key=>$value){
            if(isset($depart_list[$value['depart_id']])) {
                if(!isset($depart_list[$value['depart_id']]['use_end_time'])){
                    $depart_list[$value['depart_id']]['depart_id'] = $value['depart_id'];
                    $depart_list[$value['depart_id']]['use_end_time'] = changeDate($value['use_end_time']);
                    $depart_list[$value['depart_id']]['status'] = $value['can_examine_status'];
                    $depart_list[$value['depart_id']]['status_str'] = $can_examine_status_str[$value['can_examine_status']];
                }

                $depart_list[$value['depart_id']]['amount_count']++;
                if($value['status'] == 1){
                    $depart_list[$value['depart_id']]['complete_count']++;
                }
                //如果该考核没有主动操作结束，则使用已完成数与总数进行比较判断是否已结束
                if($value['can_examine_status'] == 0){
                    if($depart_list[$value['depart_id']]['amount_count'] == $depart_list[$value['depart_id']]['complete_count']){
                        $depart_list[$value['depart_id']]['status'] = 1;
                        $depart_list[$value['depart_id']]['status_str'] = $can_examine_status_str[1];
                    }else{
                        $depart_list[$value['depart_id']]['status'] = 0;
                        $depart_list[$value['depart_id']]['status_str'] = $can_examine_status_str[0];
                    }
                }
            }
        }
        $depart_list = array_values($depart_list);

        $this->successReturn("获取成功",$depart_list);
    }

    /**
     * 设置该部门的下级审核状态结束
     */
    public function setDepartStatusStop(){
        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");
        $depart_id = $_REQUEST['depart_id'] ? $_REQUEST['depart_id'] : $this->errorReturn("缺少部门ID");

        $update_result = M("MidExamineDownRelation")
            ->where(['mid_ex_id'=>$mid_ex_id,'depart_id'=>$depart_id])
            ->setField("can_examine_status",1);
        if($update_result){
            $this->successReturn("设置结束成功");
        }else{
            $this->errorReturn("设置失败，请重新尝试");
        }
    }

    /**
     * 删除中层考核临时账号接口
     */
    public function deleteDepartDownAction(){
        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");

        $depart_id_str = $_REQUEST['depart_id_str']?$_REQUEST['depart_id_str']:$this->errorReturn("请传入需要删除临时账号的部门ID");

        $depart_id_array = explode(",",$depart_id_str);
        if(!$depart_id_array){
            $this->errorReturn("请传入需要删除临时账号的部门ID");
        }

        $user_id_array = M("MidExamineDownRelation")
            ->where(['mid_ex_id'=>$mid_ex_id,'depart_id'=>['in',$depart_id_array]])
            ->getField("examine_user_id",true);

        $model = M();
        $model->startTrans();

        $delete_user_result = M("User")
            ->where(['user_id'=>['in',$user_id_array]])
            ->delete();

        if(!$delete_user_result){
            $model->rollback();
            $this->errorReturn("删除临时账号失败，请重新尝试");
        }

        $delete_mid_examine_down_relation = M("MidExamineDownRelation")
            ->where(['mid_ex_id'=>$mid_ex_id,'depart_id'=>['in',$depart_id_array]])
            ->delete();
        if(!$delete_mid_examine_down_relation){
            $model->rollback();
            $this->errorReturn("删除下级关系失败，请重新尝试");
        }

        $model->commit();
        $this->successReturn("删除成功");
    }

    /**
     * 获取上级考核情况列表
     */
    public function getUpUserInfoList(){
        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");

        $mid_ex_data = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("up_start_time,up_end_time")
            ->find();

        $up_user_list = M("User")
            ->where(['rank'=>['in','4,5']])
            ->order("user_id,rank desc")
            ->field("user_id,depart_id,name,rank,station,station_type")
            ->select();

        if(!$up_user_list){
            $this->returnJson(503,"无上级人员数据");
        }

        $depart_id_array = array_column($up_user_list,'depart_id');
        $depart_name_array = M("Department")
            ->where(['depart_id'=>['in',$depart_id_array]])
            ->getField("depart_id,name");

        foreach($up_user_list as $key=>$value){
            $up_user_list[$key]['rank'] = CommonModel::rank_str_array[$value['rank']];
            $up_user_list[$key]['depart_name'] = $depart_name_array[$value['depart_id']];

            $up_user_list[$key]['examine_count'] = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'examine_user_id'=>$value['user_id']])
                ->count();

            $up_user_list[$key]['no_complete_count'] = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'examine_user_id'=>$value['user_id'],'status'=>0])
                ->count();
        }

        $return_data = array();
        $return_data['list_data'] = $up_user_list;
        $return_data['start_time'] = changeDate($mid_ex_data['up_start_time']);
        $return_data['end_time'] = changeDate($mid_ex_data['up_end_time']);

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 设置考核状态
     */
    public function setExamineStatus(){
        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");
        $status = $_REQUEST['status']?$_REQUEST['status']:$this->errorReturn("缺少状态参数");

        $check_time = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("status,same_start_time,same_end_time,up_start_time,up_end_time")
            ->find();

        $current_time = time();

        if($status == 1){
            //检查考核状态是否为未开始
            if($check_time['status'] != 0) {
                $this->errorReturn("该考核进行中，无法再次开始");
            }
            //检查是否设置了中层互评时间
            if($check_time['same_start_time'] == 0){
                $this->errorReturn("该考核未设置中层互评考核时间，请先设置中层互评考核时间");
            }
            //检查是否设置了高层考核时间
            if($check_time['up_start_time'] == 0){
                $this->errorReturn("该考核未设置高层考核时间，请先设置高层考核时间");
            }
            //检查是否设置了临时审核账号
            $check_is_set_temporary_user = M("MidExamineDownRelation")
                ->where(['mid_ex_id'=>$mid_ex_id])
                ->count();
            if(!$check_is_set_temporary_user){
                $this->errorReturn("该考核未设置下级临时账号审核,请前往设置");
            }
            //检查是否设置了中层互评关系
            $check_is_set_same_relation = M("MidExamineSameRelation")
                ->where(['mid_ex_id'=>$mid_ex_id])
                ->count();
            if(!$check_is_set_same_relation){
                $this->errorReturn("该考核未设置中层互评关系,请前往设置");
            }
            //检查是否设置了高级考核关系
            $check_is_set_up_relation = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id])
                ->count();
            if(!$check_is_set_up_relation){
                $this->errorReturn("该考核未设置高级考评关系,请前往设置");
            }
            $update_result = M("MidExamine")
                ->where(['mid_ex_id'=>$mid_ex_id])
                ->setField("status",1);
            if(!$update_result){
                $this->errorReturn("修改状态失败");
            }
        }else if($status == 2){
            if($check_time['status'] != 1){
                $this->errorReturn("该考核未开始，无法进行结束操作");
            }
            //检查是否设置了最终考核权重参数
            $check_weight_data = M("MidExamineResult")
                ->where(['mid_ex_id'=>$mid_ex_id])
                ->count();
            if(!$check_weight_data){
                $this->errorReturn("该考核未设置最终结果权重，请前往设置");
            }
            $update_result = M("MidExamine")
                ->where(['mid_ex_id'=>$mid_ex_id])
                ->setField("status",2);
            if(!$update_result){
                $this->errorReturn("修改状态失败");
            }
        }else{
            $this->errorReturn("状态参数错误");
        }

        $this->successReturn("修改成功");
    }

    /**
     * 获取  "被" 考核中层干部列表
     * 与上面的getMidUserList接口，审核与被审核关系相反
     */
    public function getBeExamineMidUserList(){
        //分页
        $now_page = $_REQUEST['now_page']?$_REQUEST['now_page']:1;//默认第一页
        $page_size = $_REQUEST['page_size']?$_REQUEST['page_size']:50;//默认每页50条
        //是否获取全部
        $is_all = $_REQUEST["is_all"]?$_REQUEST["is_all"]:0;

        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");

        $mid_ex_data = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("same_start_time,same_end_time")
            ->find();

        $hide_user_id = $_REQUEST['hide_user_id'] ? $_REQUEST['hide_user_id'] : 0;

        $where = array();
        //筛选部门
        if($_REQUEST["search_depart_id"]){
            $where['depart_id'] = $_REQUEST['search_depart_id'];
        }
        //筛选级别
        if($_REQUEST["search_rank"] && ($_REQUEST["search_rank"] == 3 || $_REQUEST["search_rank"] == 4)){
            $where['rank'] = $_REQUEST['search_rank'];
        }else{
            $where['rank'] = ['in','3,4'];
        }
        //筛选姓名
        if($_REQUEST["search_name"]){
            $where['name'] = ['like','%'.$_REQUEST['search_name'].'%'];
        }
        //筛选职务
        if($_REQUEST["search_station"]){
            $where['station'] = ['like','%'.$_REQUEST['search_station'].'%'];
        }

        $examine_user_id_list = array();
        if($hide_user_id){
            $where['user_id'] = ['neq',$hide_user_id];

            $examine_user_id_list = M("MidExamineSameRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$hide_user_id])
                ->getField("examine_user_id",true);
            if(!$examine_user_id_list){
                $examine_user_id_list = array();
            }
        }

        $field = "user_id,depart_id,number,name,phone,email,rank,station,station_type";

        if($is_all){
            $list_data = M("User")
                ->where($where)
                ->order("user_id")
                ->field($field)
                ->select();
        }else{
            $list_data = M("User")
                ->where($where)
                ->order("user_id")
                ->field($field)
                ->page($now_page,$page_size)
                ->select();
        }

        if(!$list_data){
            $this->returnJson(503,'没有更多数据');
        }

        $depart_name_array = array();
        if($list_data){
            $depart_id_array = array_column($list_data,'depart_id');

            $depart_name_array = M("Department")
                ->where(['depart_id'=>['in',$depart_id_array]])
                ->getField("depart_id,name");
        }

        foreach($list_data as $key=>$value) {
            $list_data[$key]['depart_name'] = isset($depart_name_array[$value['depart_id']])?$depart_name_array[$value['depart_id']]:"";

            $list_data[$key]['rank'] = CommonModel::rank_str_array[$value['rank']];

            $list_data[$key]['examine_mid_count'] = M("MidExamineSameRelation")
                ->where(['mid_ex_id' => $mid_ex_id, 'examine_user_id' => $value['user_id']])
                ->count();
            $list_data[$key]['examine_mid_complete_count'] = M("MidExamineSameRelation")
                ->where(['mid_ex_id' => $mid_ex_id, 'examine_user_id' => $value['user_id'],'status'=>1])
                ->count();
            if($list_data[$key]['examine_mid_count'] == 0){
                $list_data[$key]['examine_mid_result'] = "";
            }else{
                if($list_data[$key]['examine_mid_count'] == $list_data[$key]['examine_mid_complete_count']){
                    $list_data[$key]['examine_mid_result'] = "已完成";
                }else{
                    $list_data[$key]['examine_mid_result'] = "未完成";
                }
            }

            $list_data[$key]['be_examine_mid_count'] = M("MidExamineSameRelation")
                ->where(['mid_ex_id' => $mid_ex_id, 'be_examine_user_id' => $value['user_id']])
                ->count();
            $list_data[$key]['be_examine_mid_complete_count'] = M("MidExamineSameRelation")
                ->where(['mid_ex_id' => $mid_ex_id, 'be_examine_user_id' => $value['user_id'],'status'=>1])
                ->count();
            if($list_data[$key]['be_examine_mid_count'] == 0){
                $list_data[$key]['be_examine_mid_result'] = "";
            }else{
                if($list_data[$key]['be_examine_mid_count'] == $list_data[$key]['be_examine_mid_complete_count']){
                    $list_data[$key]['be_examine_mid_result'] = "已完成";
                }else{
                    $list_data[$key]['be_examine_mid_result'] = "未完成";
                }
            }

            $list_data[$key]['examine_up_count'] = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$value['user_id']])
                ->count();
            $list_data[$key]['examine_up_complete_count'] = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$value['user_id'],'status'=>1])
                ->count();

            if($list_data[$key]['examine_up_count'] == 0){
                $list_data[$key]['examine_up_result'] = "";
            }else{
                if($list_data[$key]['examine_up_count'] == $list_data[$key]['examine_up_complete_count']){
                    $list_data[$key]['examine_up_result'] = "已完成";
                }else{
                    $list_data[$key]['examine_up_result'] = "未完成";
                }
            }
        }

        $count = M('User')
            ->where($where)
            ->count();

        $return_data = array();
        $return_data['list_data'] = $list_data;
        $return_data['examine_user_id_list'] = $examine_user_id_list;
        $return_data['start_time'] = changeDate($mid_ex_data['same_start_time']);
        $return_data['end_time'] = changeDate($mid_ex_data['same_end_time']);
        $return_data['count'] = $count;
        $return_data['now_page'] = $now_page;
        $return_data['page_size'] = $page_size;
        $return_data['max_page'] = ceil($count / $page_size);

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 获取最终考核结果接口
     */
    public function finalResultList(){
        //必要参数
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");

        $examine_item_count = M("MidExamineItem")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->count();
        if(!$examine_item_count){
            $this->errorReturn("中层考核ID错误");
        }
        //考核满分
        $examine_full_marks = $examine_item_count * 10;

        //分页
        $now_page = $_REQUEST['now_page']?$_REQUEST['now_page']:1;//默认第一页
        $page_size = $_REQUEST['page_size']?$_REQUEST['page_size']:50;//默认每页50条

        //查询条件
        $where = array();
        //筛选中层员工
        if($_REQUEST["search_user_id"]){
            $where['user_id'] = $_REQUEST["search_user_id"];
        }
        //筛选级别
        if($_REQUEST["search_rank"] == 3 || $_REQUEST["search_rank"] == 4){
            $where['rank'] = $_REQUEST["search_rank"];
        }else{
            $where['rank'] = ['in','3,4'];
        }
        //筛选干部名称
        if($_REQUEST["search_name"]){
            $where['name'] = ['like','%'.$_REQUEST['search_name'].'%'];
        }
        //筛选职务
        if($_REQUEST["search_station"]){
            $where['station'] = ['like','%'.$_REQUEST['search_station'].'%'];
        }

        $field = "user_id,depart_id,number,name,rank,station,station_type";

        $list_data = M("User")
            ->where($where)
            ->page($now_page,$page_size)
            ->order("user_id")
            ->field($field)
            ->select();

        if(!$list_data){
            $this->returnJson(503,"无数据");
        }

        $depart_id_array = array_column($list_data,"depart_id");
        $depart_name_array = M("Department")
            ->where(['depart_id'=>['in',$depart_id_array]])
            ->getField("depart_id,name");

        $final_result_user_data = M("MidExamineResult")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->getField("be_examine_user_id,up_weight,same_weight,down_weight,manage_score,full_manage_score,result_type");
        if(!$final_result_user_data){
            $final_result_user_data = array();
        }

        foreach($list_data as $key=>$value){
            $list_data[$key]['depart_name'] = $depart_name_array[$value['depart_id']];
            $list_data[$key]['rank'] = CommonModel::rank_str_array[$value['rank']];
            //统计下级最终的分
            $list_data[$key]['down_score'] = 0;
            $down_examine_result = M("MidExamineDownRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$value['user_id'],'status'=>1])
                ->field("score")
                ->select();
            if($down_examine_result){
                $down_amount_score = 0;
                foreach($down_examine_result as $key2=>$value2){
                    $down_amount_score = bcadd($down_amount_score,$value2['score'],4);
                }
                $down_examine_count = count($down_examine_result);
                $list_data[$key]['down_score'] = round(bcdiv($down_amount_score,$down_examine_count,4),2);
            }

            //统计中层互评最终得分
            $list_data[$key]['same_score'] = 0;
            $same_examine_result = M("MidExamineSameRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$value['user_id'],'status'=>1])
                ->field("examine_result,score")
                ->select();
            if($same_examine_result){
                $same_amount_score = 0;
                foreach($same_examine_result as $key2=>$value2){
                    $same_amount_score = bcadd($same_amount_score,$value2['score'],4);
                }
                $same_examine_count = count($same_examine_result);
                $list_data[$key]['same_score'] = round(bcdiv($same_amount_score,$same_examine_count,4),2);
            }

            //统计上级最终得分
            $list_data[$key]['up_score'] = 0;
            $up_examine_result = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$value['user_id']])
                ->field("status,weight_score")
                ->order('up_type')          //确保直接上级在循环中处于末尾
                ->select();
            if($up_examine_result){
                $up_amount_score = 0;
                foreach($up_examine_result as $key2=>$value2){
                    if($value2['status'] == 1){
                        $up_amount_score = bcadd($up_amount_score,$value2['weight_score'],4);
                    }else{
                        //有上级没有完成评审
                        $up_amount_score = -1;
                        break;
                    }
                }
                if($up_amount_score != -1){
                    $list_data[$key]['up_score'] = $up_amount_score;
                }
            }

            if(isset($final_result_user_data[$value['user_id']])){
                $list_data[$key]['down_weight'] = bcmul($final_result_user_data[$value['user_id']]['down_weight'],100);
                $list_data[$key]['same_weight'] = bcmul($final_result_user_data[$value['user_id']]['same_weight'],100);
                $list_data[$key]['up_weight'] = bcmul($final_result_user_data[$value['user_id']]['up_weight'],100);

                $down_weight_score = bcmul($list_data[$key]['down_score'],$final_result_user_data[$value['user_id']]['down_weight'],4);
                $same_weight_score = bcmul($list_data[$key]['same_score'],$final_result_user_data[$value['user_id']]['same_weight'],4);
                $up_weight_score = bcmul($list_data[$key]['up_score'],$final_result_user_data[$value['user_id']]['up_weight'],4);

                $final_examine_score = round(bcadd(bcadd($down_weight_score,$same_weight_score,4),$up_weight_score,4),2);

                $list_data[$key]['final_examine_score'] = $final_examine_score;
                $list_data[$key]['percentile_score'] = round(bcmul(bcdiv($final_examine_score,$examine_full_marks,4),100,4),2);
                $list_data[$key]['manage_score'] = $final_result_user_data[$value['user_id']]['manage_score'];
                $list_data[$key]['full_manage_score'] = $final_result_user_data[$value['user_id']]['full_manage_score'];
                $list_data[$key]['percentile_manage_score'] = round(
                    bcmul(
                        bcdiv($final_result_user_data[$value['user_id']]['manage_score'],
                            $final_result_user_data[$value['user_id']]['full_manage_score'],4)
                        ,100,4)
                    ,2);

                if($list_data[$key]['percentile_manage_score'] > 0){

                    $list_data[$key]['final_score'] = round(bcadd(bcmul($list_data[$key]['percentile_score'],0.7,4),
                        bcmul($list_data[$key]['percentile_manage_score'],0.3,4),
                        4),2);
                }else{
                    $list_data[$key]['final_score'] = $list_data[$key]['percentile_score'];
                }

                $list_data[$key]['result_type'] = $final_result_user_data[$value['user_id']]['result_type'];
            }else{
                $list_data[$key]['down_weight'] = 0;
                $list_data[$key]['same_weight'] = 0;
                $list_data[$key]['up_weight'] = 0;

                $list_data[$key]['final_examine_score'] = 0;
                $list_data[$key]['percentile_score'] = 0;
                $list_data[$key]['manage_score'] = 0;
                $list_data[$key]['full_manage_score'] = 0;
                $list_data[$key]['percentile_manage_score'] = 0;

                $list_data[$key]['final_score'] = 0;

                $list_data[$key]['result_type'] = "";
            }
        }

        $count = M("User")
            ->where($where)
            ->count();

        $return_data = array();
        $return_data['list_data'] = $list_data;
        $return_data['count'] = $count;
        $return_data['now_page'] = $now_page;
        $return_data['page_size'] = $page_size;
        $return_data['max_page'] = ceil($count / $page_size);

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 获取考核主页概览数据
     */
    public function getExamineBaseInfo(){
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");

        $examine_data = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->find();

        $down_examine_info = M("MidExamineDownRelation")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("examine_user_id,status")
            ->group("examine_user_id")
            ->select();
        if($down_examine_info){
            $down_release_count = count($down_examine_info);

            $down_complete_count = 0;
            foreach($down_examine_info as $key=>$value){
                if($value['status'] == 1){
                    $down_complete_count++;
                }
            }
        }else{
            $down_release_count = 0;
            $down_complete_count = 0;
        }

        $same_examine_info = M("MidExamineSameRelation")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("examine_user_id,status")
            ->group("examine_user_id")
            ->select();
        if($same_examine_info){
            $same_release_count = count($same_examine_info);

            $same_complete_count = 0;
            foreach($same_examine_info as $key=>$value){
                if($value['status'] == 1){
                    $same_complete_count++;
                }
            }
        }else{
            $same_release_count = 0;
            $same_complete_count = 0;
        }

        $up_examine_info = M("MidExamineUpRelation")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("examine_user_id,status")
            ->group("examine_user_id")
            ->select();
        if($up_examine_info){
            $up_release_count = count($up_examine_info);

            $up_complete_count = 0;
            foreach($up_examine_info as $key=>$value){
                if($value['status'] == 1){
                    $up_complete_count++;
                }
            }
        }else{
            $up_release_count = 0;
            $up_complete_count = 0;
        }

        $examine_status_str_array = ["未开始","进行中","已结束"];
        $return_data = array();
        $return_data['examine_status'] = $examine_data['status'];
        $return_data['examine_status_str'] = $examine_status_str_array[$examine_data['status']];
        $return_data['same_start_time'] = changeDate($examine_data['same_start_time']);
        $return_data['same_end_time'] = changeDate($examine_data['same_end_time']);
        $return_data['up_start_time'] = changeDate($examine_data['up_start_time']);
        $return_data['up_end_time'] = changeDate($examine_data['up_end_time']);
        $return_data['down_release_count'] = $down_release_count;
        $return_data['down_complete_count'] = $down_complete_count;
        $return_data['same_release_count'] = $same_release_count;
        $return_data['same_complete_count'] = $same_complete_count;
        $return_data['up_release_count'] = $up_release_count;
        $return_data['up_complete_count'] = $up_complete_count;

        $this->successReturn("获取成功",$return_data);
    }
}